package com.cloudtasks;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;

import com.cloudtasks.shared.CloudTasksRequestFactory;
import com.cloudtasks.shared.TaskProxy;
import com.cloudtasks.shared.TaskRequest;
import com.google.web.bindery.requestfactory.shared.Receiver;


public class AsyncSendTask extends AsyncTask<String, Void, Long> {

    private final UsersDisplayActivity activity;
    private boolean newTask = false;
    long id;
    
    public AsyncSendTask(UsersDisplayActivity usersDisplayActivity) {
        super();
        this.activity = usersDisplayActivity;
    }

    @Override
    protected Long doInBackground(String... arguments) {
       // final List<TaskProxy> list = new ArrayList<TaskProxy>();
        // INSERT RPC HERE!
        CloudTasksRequestFactory factory = Util.getRequestFactory(activity,
        		CloudTasksRequestFactory.class);
        
        TaskRequest request = factory.taskRequest();
        TaskProxy my_task = request.create(TaskProxy.class);
        
        my_task.setName(arguments[0]);
      //  if (arguments.length == 0 || arguments[0] == -1) 
        //{
	        //System.out.println("I'm here...AsyncSend");
	        //Send new user
        	request.updateTask(my_task).fire(new Receiver<TaskProxy>() {
				@Override
				public void onSuccess(TaskProxy arg0) {
					//list.addAll(arg0);
					System.out.println("I'm here async send task...AsyncSend");
					id = arg0.getId();
					//my_task.setId(arg0.getId());
				}
	        });
      //  } 
       // my_task.setId(id);
        return id;
    }

    @Override
    protected void onPostExecute(Long result) {
    	//if (newTask) {
    		//activity.compare_users(result);
    	//} else {
    	synchronized (activity) {
			  activity.notify();
			}
    	//activity.notify();
    	activity.update_user(result);
    	activity.sync_count.decrement();
    	//activity.notify();
		System.out.println("Decremented sync = "+ activity.sync_count.value());	
    		
    	//}
    }
}
